package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.query.impl.MenuQuery;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {
    @Autowired
    MenuMapper menuMapper;


    public void delete(Long id) {
        menuMapper.deleteByPrimaryKey(id);
    }

    public void saveOrUpdate(Menu record) {
        if (record.getId() == null) {
            menuMapper.insert(record);
        } else {
            menuMapper.updateByPrimaryKey(record);
        }
    }

    public Menu get(Long id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    public List<Menu> getAll(MenuQuery query) {
        return menuMapper.selectAll(query);
    }

    public List<Menu> selectRootMenu(){return menuMapper.selectRootMenu();}

    public List<Menu> selectEmployeeMenu() {
        //查询出所有的菜单
        List<Menu> menus = menuMapper.selectRootMenu();
        //判断当前登录用户是否是管理员
        Employee currentUser = UserContext.getCurrentUser();
        //如果不是,就需要对菜单做权限控制
        if(!currentUser.isAdmin()) {
            //ids是当前员工拥有的菜单id集合
            List<Long> ids = menuMapper.selectByEmployeeId(currentUser.getId());
            checkMenu(menus,ids);
        }
        return menus;
    }
    //抽取方法对其进行递归
    public void checkMenu(List<Menu> menus,List<Long> ids){
        Iterator<Menu> it = menus.iterator();
        while (it.hasNext()) {
            Menu menu = it.next();
            //判断菜单的id是否存在ids中
            if (!ids.contains(menu.getId())) {
                it.remove();
                continue;
            }
            //递归判断子菜单的权限
            if(menu.getChildren().size()>0) {
                checkMenu(menu.getChildren(), ids);
            }
        }
    }

}
